import { usePage } from '@/hooks'
import { useUserStore } from './user'
import { pinia } from '@/store'
import { PageEnum } from '@/constants'

export const useLockStore = defineStore(
	'lock',
	() => {
		const lockInfo = ref<null | StoreType.LockState>(null)

		//设置
		const setLockInfo = async (info: StoreType.LockState) => {
			lockInfo.value = Object.assign({}, lockInfo.value, info)
		}
		// 重置
		const resetLockInfo = async () => {
			lockInfo.value = null
		}
		const { routerGo } = usePage(false)
		const resetLockAndPush = async () => {
			const link = lockInfo.value?.link ? lockInfo.value.link : PageEnum.BASE_HOME
			await resetLockInfo()
			await routerGo(link, true)
		}
		// 解锁
		const unLock = async function (password?: string) {
			const { userInfo, login } = useUserStore()
			if (lockInfo.value?.pwd === password) {
				await resetLockAndPush()
				return true
			}
			const tryLogin = async () => {
				try {
					const username = userInfo?.username ?? ''
					const res = await login({
						username,
						password: password!,
						goHome: false,
						mode: 'none'
					})
					if (res) {
						await resetLockAndPush()
					}
					return res
				} catch (error) {
					return false
				}
			}
			return await tryLogin()
		}
		return { lockInfo, setLockInfo, resetLockInfo, unLock }
	},
	{
		persist: true
	}
)
// 在组合式setup之外使用
export function useLockStoreWithout() {
	return useLockStore(pinia)
}
